package cn.itcast.oa.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import cn.itcast.oa.base.BaseDAOimpl;
import cn.itcast.oa.model.Forum;
import cn.itcast.oa.service.ForumService;

@Service
@SuppressWarnings("unchecked")
public class ForumServiceImpl extends BaseDAOimpl<Forum> implements ForumService {
  
	
	@Override
	public List<Forum> findAll(){
		return getSession().createQuery(//
				"FROM Forum f ORDER BY f.position ASC")//
				.list();
	}
	@Override
	public void save(Forum forum){
		getSession().save(forum);
		forum.setPosition(forum.getId().intValue());
	}
	
	/**
	 * 上移
	 */
	@Override
	public void moveUp(Long id) {
		// TODO Auto-generated method stub
		Forum forum=getById(id);
		Forum other=(Forum) getSession().createQuery(
				"FROM Forum f WHERE f.position<? ORDER BY f.position DESC")
				.setParameter(0, forum.getPosition())
				.setFirstResult(0)
				.setMaxResults(1)
				.uniqueResult();
		if(other==null){
			return;
		}
		int temp=forum.getPosition();
		forum.setPosition(other.getPosition());
		other.setPosition(temp);
	}
    
	/**
	 * 下移
	 */
	@Override
	public void moveDown(Long id) {
		// TODO Auto-generated method stub
		Forum forum=getById(id);
		Forum other=(Forum) getSession().createQuery(//
				"FROM Forum f WHERE f.position>? ORDER BY f.position ASC")//
				.setParameter(0, forum.getPosition())
				.setFirstResult(0)
				.setMaxResults(1)
				.uniqueResult();
		if(other==null){
			return;
		}
		int temp=forum.getPosition();
		forum.setPosition(other.getPosition());
		other.setPosition(temp);
	}
    
}
